<?php

namespace App\Listeners;

use App\Events\OperationLogEvent;
use App\Kuafu\Common\Model\OperationLogRecordModel;
use App\Library\OperationLog\OperationLog;

class OperationLogListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param OperationLogEvent $operationLogEvent
     * @return void
     */
    public function handle(OperationLogEvent $operationLogEvent)
    {
        $operationLogInsert = [
            "route_file"       => "",
            "route"            => $operationLogEvent->request->getRequestUri(),
            "request_method"   => $operationLogEvent->request->method(),
            "request_params"   => collect($operationLogEvent->request->all())
                ->except("s")
                ->toJson(JSON_UNESCAPED_UNICODE),
            "module"           => $operationLogEvent->module,
            "name"             => class_basename($operationLogEvent->request->route()->getActionName()),
            "desc"             => $operationLogEvent->logDesc,
            "business_mark"    => "",
            'log_content'      => collect($operationLogEvent->operationLogGroup)->map(function (
                OperationLog $operationLog
            ) {
                return [
                    "title"        => $operationLog->title,
                    "changeDetail" => $operationLog->generateLogContent()
                ];
            })->toJson(JSON_UNESCAPED_UNICODE),
            "operate_userid"   => $operationLogEvent->request->user()->id,
            "operate_username" => $operationLogEvent->request->user()->username,
        ];


        OperationLogRecordModel::query()->insert($operationLogInsert);
    }
}
